<template>
  <div class="main user-layout-register">
    <h3>
      <span>找回密码</span>
    </h3>
    <a-form-model :model="form" ref="formRegister" :rules="rules" id="formRegister">
      <a-form-model-item prop="phone">
        <!-- <a-input
          size="large"
          placeholder="请输入11位手机号码"
          v-decorator="['mobile', {rules: [{ required: true, message: '请输入正确的手机号', pattern: /^1[3456789]\d{9}$/ }, { validator: this.handlePhoneCheck } ], validateTrigger: ['change', 'blur'] }]"
        >
        </a-input>-->
        <a-input
          size="large"
          @click="handlePasswordInputClick(2)"
          placeholder="请输入11位手机号码"
          v-model="form.phone"
        ></a-input>
      </a-form-model-item>
      <a-popover
        placement="rightTop"
        :trigger="['focus']"
        :getPopupContainer="(trigger) => trigger.parentElement"
        v-model="state.passwordLevelChecked"
        overlayClassName="recoverPopoverReduceZinex"
      >
        <template slot="content">
          <div :style="{ width: '240px' }" >
            <div :class="['user-register', passwordLevelClass]">
              强度：
              <span>{{ passwordLevelName }}</span>
            </div>
            <a-progress
              :percent="state.percent"
              :showInfo="false"
              :strokeColor=" passwordLevelColor "
            />
            <div style="margin-top: 10px;">
              <span>请输入6-16位密码，区分大小写。请不要使用容易被猜到的密码。</span>
            </div>
          </div>
        </template>
        <a-form-model-item prop="password">
          <a-input-password
            size="large"
            autocomplete="false"
            placeholder="请输入6-16位密码，区分大小写"
            @change="handlePasswordLevel(form.password)"
            :maxLength="16"
            @click="handlePasswordInputClick(1)"
            v-model="form.password"
          ></a-input-password>
        </a-form-model-item>
      </a-popover>
      <a-row :gutter="16">
        <a-col class="gutter-row" :span="16">
          <a-form-model-item prop="captcha">
            <a-input
              size="large"
              type="text"
              placeholder="验证码"
              v-model="form.captcha"
              @click="handlePasswordInputClick(2)"
            >
              <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <a-button
            class="getCaptcha"
            size="large"
            :disabled="state.smsSendBtn"
            @click.stop.prevent="getPicCaptcha"
            v-text="!state.smsSendBtn && '获取验证码'||(state.time+' s')"
          ></a-button>
        </a-col>
      </a-row>
      <a-form-model-item>
        <router-link class="login" :to="{ name: 'login' }">使用已有账户登录</router-link>
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="register-button"
          :loading="registerBtn"
          @click.stop.prevent="handleSubmit"
          :disabled="registerBtn"
        >确定</a-button>
      </a-form-model-item>
    </a-form-model>
    <a-modal
      :visible="visible"
      title="输入验证码"
      :closable="false"
      :confirm-loading="confirmLoading"
      @ok="getCaptcha"
      @cancel="visible=false"
      :width="400"
    >
      <a-spin :spinning="loading" class="reload">
        <a-input-group>
          <a-row type="flex" justify="space-around">
            <a-col>
              <a-input v-model="picCaptcha" placeholder="请输入右侧的验证码" />
            </a-col>
            <a-col>
              <img
                @click="reloadPicCaptcha()"
                :src="backendPicCaptcha"
                alt
                style="cursor:pointer;border-radius:4px;width:136px;height:36px;"
              />
              <p style="margin:0;padding:0;margin-top:4px;color:#bbb;">点击图片刷新验证码</p>
            </a-col>
          </a-row>
        </a-input-group>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import { getPicCaptcha, sendSms, findPwd } from '@/api/login'
// import { getSmsCaptcha } from '@/api/login'

const levelNames = {
  0: '低',
  1: '低',
  2: '中',
  3: '强',
}
const levelClass = {
  0: 'error',
  1: 'error',
  2: 'warning',
  3: 'success',
}
const levelColor = {
  0: '#ff0000',
  1: '#ff0000',
  2: '#ff7e05',
  3: '#52c41a',
}
export default {
  name: 'Register',
  components: {},
  data() {
    return {
      loading: false,
      form: {},
      backendPicCaptcha: null, //后台返回的验证码图片
      picCaptchaKey: null, //发送短信验证码时传给后台的图片验证码key
      smsKey: null, //短信验证码key
      smsCaptcha: null, //短信验证码
      rules: {
        phone: [{ required: true, pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码！' }],
        password: [
          {
            required: true,
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/,
            message: '请输入6-16位字母和数字组合(禁用标点符号)的密码！',
          },
        ],
        phone: [{ required: true, pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码！' }],
        captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
      },
      state: {
        time: 60,
        smsSendBtn: false,
        passwordLevel: 0,
        passwordLevelChecked: false,
        percent: 10,
        progressColor: '#FF0000',
      },
      picCaptcha: undefined,
      visible: false,
      timestamp: undefined,
      confirmLoading: false,
      registerBtn: false,
    }
  },
  computed: {
    passwordLevelClass() {
      return levelClass[this.state.passwordLevel]
    },
    passwordLevelName() {
      return levelNames[this.state.passwordLevel]
    },
    passwordLevelColor() {
      return levelColor[this.state.passwordLevel]
    },
  },
  methods: {
    handlePasswordLevel(value) {
      let level = 0
      if (value) {
        // 判断这个字符串中有没有数字
        if (/[0-9]/.test(value)) {
          level++
        }
        // 判断字符串中有没有小写字母
        if (/[a-z]/.test(value)) {
          level++
        }
        // 判断字符串中有没有大写符号
        if (/[A-Z]/.test(value)) {
          level++
        }
      } else {
        level = 0
      }

      this.state.passwordLevel = level
      this.state.percent = level * 30
      if (level >= 2) {
        if (level >= 3) {
          this.state.percent = 100
        }
      } else {
        if (level === 0) {
          this.state.percent = 10
        }
      }
    },
    //展示强度小窗口
    handlePasswordInputClick(type) {
      if (type == 1) {
        this.state.passwordLevelChecked = true
        return
      } else {
        if (this.state.percent >= 60) {
          this.state.passwordLevelChecked = false
        }
      }
    },
    //确认修改
    handleSubmit() {
      this.$refs.formRegister.validate((valid) => {
        if (valid) {
          if(!this.smsKey){
            this.$message.error('发送请求失败，请刷新后重试~')
            return
          }
          this.loading = true
          findPwd({
            phone: this.form.phone,
            key: this.smsKey,
            password: this.form.password,
            sms_code: this.form.captcha,
          })
            .then((res) => {
              this.$message.success('修改密码成功，请重新登录')
              this.$router.push({ name: 'login' })
            })
            .catch((err) => {
              this.$message.error(err.data.message||'修改验证码失败')
            })
        
        } else {
          return false
        }
      })
    },
    //刷新图片二维码
    reloadPicCaptcha() {
      this.timestamp = new Date().valueOf()
      getPicCaptcha().then((res) => {
        this.backendPicCaptcha = res.path
        this.picCaptchaKey = res.key
        this.loading = false
      })
    },
    //显示图片验证码弹窗
    getPicCaptcha() {
      if (this.form.phone) {
        if (/^1[3456789]\d{9}$/.test(this.form.phone)) {
          // 显示图像二维码弹窗
          this.reloadPicCaptcha()
          this.visible = true
        } else {
          this.$message.error('请输入正确的手机号码~')
        }
      } else {
        this.$message.error('请输入手机号码~')
      }
    },
    //发送手机验证码
    getCaptcha() {
      if(!this.picCaptchaKey){
        this.$message.error('发送短信二维码失败，请刷新后重试~')
        return
      }
      if (!this.picCaptcha) {
        this.$message.error('请输入验证码')
        return
      }
      const interval = window.setInterval(() => {
        if (this.state.time-- <= 0) {
          this.state.time = 60
          this.state.smsSendBtn = false
          window.clearInterval(interval)
        }
      }, 1000)
      sendSms({ phone: this.form.phone, captcha: this.picCaptcha, key: this.picCaptchaKey })
        .then((res) => {
          this.smsKey = res.key
          this.$message.loading('验证码发送中..', 0.5).then(() => {
            this.$message.success('发送成功', 2.5)
            this.state.smsSendBtn = true
            this.visible = false
          })
        })
        .catch((err) => {
          this.$message.loading('验证码发送中..', 0.5).then(() => {
            this.reloadPicCaptcha()
            clearInterval(interval)
            this.$message.error(err.data.message || '发送失败', 2.5)
            this.state.time = 60
            this.state.smsSendBtn = false
            // this.requestFailed(err)
          })
        })
    },
    //报错
    // requestFailed(err) {
    //   this.$notification['error']({
    //     message: '错误',
    //     description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
    //     duration: 4,
    //   })
    //   this.registerBtn = false
    // },
  },
  watch: {
    'state.percent'(val) {
      console.log(val)
    },
    visible(val) {
      if (val) {
        this.timestamp = new Date().valueOf()
      } else {
        this.captcha = undefined
        this.loading = false
      }
    },
  },
}
</script>
<style lang="less">
.recoverPopoverReduceZinex{
  z-index:999 !important
}
.user-register {
  &.error {
    color: #ff0000;
  }

  &.warning {
    color: #ff7e05;
  }

  &.success {
    color: #52c41a;
  }
}

.user-layout-register {
  .ant-input-group-addon:first-child {
    background-color: #fff;
  }
}
</style>
<style lang="less" scoped>
.user-layout-register {
  & > h3 {
    font-size: 16px;
    margin-bottom: 20px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .register-button {
    width: 50%;
    float: right;
  }

  .login {
    line-height: 40px;
  }
}
</style>
